package com.example.authority.controller;

import cn.hutool.core.util.StrUtil;


import com.example.commons.entity.dto.GeneratorDto;
import com.example.commons.entity.dto.Options;
import com.example.commons.entity.dto.TableInfo;
import com.example.authority.service.DatabaseService;
import com.example.authority.service.GeneratorService;
import com.example.commons.annotations.ClearPerms;
import com.example.commons.common.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: authority-v3.0.7
 * @ClassName:GeneratorController
 * @description: 代码生成器前端控制器
 * @author:dyy
 * @Version 3.0
 **/

@Slf4j
@RestController
@RequestMapping("/generator")
public class GeneratorController {
    @Resource
    private GeneratorService generatorService;
    @Resource
    private DatabaseService databaseService;

    @PostMapping
    @ClearPerms
    public Result generator(@RequestBody GeneratorDto generatorDto) throws SQLException, ClassNotFoundException, InterruptedException, IOException {
        generatorService.generatorCode(generatorDto);
        return Result.success();
    }


    /**
     * 获取当前数据库中的所有表以及所有列
     * @return
     */
    @GetMapping("/tables")
    public Result getAllTablesAndColumns() {
        List<TableInfo> tableInfos = databaseService.getAllTables();
        List<Options> options=new ArrayList<>();
        for (TableInfo tableInfo : tableInfos) {
            Options option=new Options().toBuilder().label(tableInfo.getTableName()).value(tableInfo.getTableName()).build();
            tableInfo.getColumns().stream().forEach(columnInfo -> {
                option.getChildren().add(new Options().toBuilder().value(columnInfo.getDataType()+"/"+StrUtil.toCamelCase(columnInfo.getColumnName())).label(StrUtil.toCamelCase(columnInfo.getColumnName())).build());
            });
            options.add(option);
        }
        return Result.success(options);
    }
}